const http = require("http");
const url = require("url");
const fs = require("fs");
const mime = require("mime");
const path = require("path");
const qs = require("querystring");

http.createServer(function(req, res) {
 	res.render = function(filePath) {
 		let contentType = mime.getType(filePath);

 		if (contentType) {
 			res.setHeader("Content-Type", contentType);
 		}

 		fs.readFile(path.join(__dirname, filePath), function(err,data) {
 			if (!err) {
 				res.end(data);
 			}else {
 				throw err;
 			}
 		});
 	}

 	const urlObj = url.parse(req.url);
 	let pathname = urlObj.pathname;
 	console.log(pathname, req.method);
 	if(pathname == "/"){
 		res.render("./public/index.html");
 	} else if (pathname.startsWith("/public/")) {
 		res.render(pathname);
 	} else if(pathname == "/img" && req.method == "POST") {
 		var str ="";
 		req.on("data", function(chunk) {
 			str += chunk;
 		});
 		req.on("end", function(){
 			var obj = qs.parse(str);

 			var base64Str = obj.imageData;

 			var data = Buffer.from(base64Str, "base64");

 			var filePath = path.join(__dirname,"public", "img", obj.name);
 			fs.writeFile(filePath, data, function(err) {
 				if(!err) {
 					res.end("success");
 				}else {
 					throw err;
 				}
 			});
 		});
 	} else {
 		res.end("404 not found");
 	}




}).listen(8080, function(err) {
	console.log("http://localhost:8080");
});